package com.atsmart.app.receiver;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Calendar;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.net.NetworkInfo;
import android.util.Log;
import com.atsmart.app.BizApp;
import com.atsmart.app.R;
import com.atsmart.app.exception.BizException;
import com.atsmart.app.http.HttpHelper;
import com.atsmart.app.model.CommonBody;
import com.atsmart.app.model.PositionAttributeInfo;
import com.atsmart.app.model.PositionInfo;
import com.atsmart.app.model.PositionShutDownInfo;
import com.atsmart.app.model.PositonsInfo;
import com.atsmart.app.service.CheckingService;
import com.atsmart.app.sql.PositionSqlHelper;
import com.atsmart.app.sql.ShutDownSqlHelper;
import com.atsmart.app.utils.LocationUtils;
import com.atsmart.app.utils.StringUtil;
import com.atsmart.app.webservice.ServiceHost;
//import com.atsmart.log.UserLog;
import com.google.json.Gson;

public class NetworkConnectedReceiver extends BroadcastReceiver {

	private static final String s_connectChange = "android.net.conn.CONNECTIVITY_CHANGE";
	private static final String s_networkInfo = "networkInfo";

	public NetworkConnectedReceiver() {

	}

	public static long time = 0;

	@Override
	public void onReceive(Context context, Intent intent) {
		try {
//			if (!BizApp.getInstance().isServiceRun()) {
				Intent i = new Intent(context, CheckingService.class);
				i.putExtra("isfromlogin", "2");
				context.startService(i);
//			}
			try {
				postOnService();
				BizApp.getInstance().keeping = true;
			} catch (Exception e) {
//				UserLog.getInstance().writeException(e);
				BizApp.getInstance().keeping = false;
			}
			String strNetworkInfo = intent.getAction();
			if (strNetworkInfo.equals(s_connectChange)) {
				NetworkInfo ni = intent.getParcelableExtra(s_networkInfo);
				if (ni != null) {
					if (checkSheetTime()) {
						if (time != 0) {
							if ((Calendar.getInstance().getTimeInMillis() - time) < 3000) {
								time = Calendar.getInstance().getTimeInMillis();
								return;
							}
						}
						time = Calendar.getInstance().getTimeInMillis();
						// Log.e("ni.isConnected()",
						// String.valueOf(ni.isConnected()));
						if (ni.isConnected()) {
							// Log.e("网络开启", "网络开启");
//							UserLog.getInstance().write("网络变换--开启");
							start_end();
						} else {
//							UserLog.getInstance().write("网络变换--关闭");
							Gson gson = new Gson();
							CommonBody body = new CommonBody();
							body.setCommand(2);
							body.setImsi(BizApp.getInstance().getIMSI());
							body.setVersion(BizApp.getInstance().getString(
									R.string.app_version));
							PositonsInfo positions = new PositonsInfo();
							positions.positions = new ArrayList<PositionInfo>();
							PositionInfo position = new PositionInfo();
							position.date = StringUtil.millToDate(Calendar
									.getInstance().getTimeInMillis());
							position.lat = 0;
							position.lon = 0;
							position.address = BizApp.getInstance()
									.getAddress();
							position.locationMsg = LocationUtils.getInstance()
									.getLocationMsg();
							position.msgType = 6;
							position.type = 1;
							positions.positions.add(position);
							ShutDownSqlHelper psql = new ShutDownSqlHelper();
							psql.open(BizApp.getInstance().getSqlHelper());
							PositionShutDownInfo pinfo = new PositionShutDownInfo();
							pinfo.setVer(gson.toJson(body));
							pinfo.setPos(gson.toJson(positions));
							pinfo.setType(3);
							psql.addAttribute(pinfo);

							// Log.e("网络关闭", " from sql gson: = " +
							// psql.getAttribute(2).getPos());
							BizApp.getInstance().setNetworkEnabled(false);

						}
					}
				}
			}
		} catch (Exception e) {
//			UserLog.getInstance().writeException(e);
		}
	}

	protected void postOnService() throws MalformedURLException, IOException,
			BizException {
		HttpHelper http = new HttpHelper();
		http.setCONNECTION_TIMEOUT(3000);
		http.setREAD_TIMEOUT(3000);
		http.createMode().url(ServiceHost.keepURL())
				.header("Content-Type", "charset=ISO-8859-1")
				.header("Accept-Charset", "ISO-8859-1");
		byte[] bb = "1".getBytes("ISO-8859-1");
		http.body(new ByteArrayInputStream(bb)).send();

	}

	private void start_end() {
		Log.e("网络开启", "网络开启");
		try{
			
		new Thread() {
				@Override
				public void run() {
					super.run();

					try {
						Gson gson = new Gson();
						CommonBody body = new CommonBody();
						body.setCommand(2);
						body.setImsi(BizApp.getInstance().getIMSI());
						body.setVersion(BizApp.getInstance().getString(
								R.string.app_version));

						PositonsInfo positions = new PositonsInfo();
						positions.positions = new ArrayList<PositionInfo>();
						PositionInfo position = new PositionInfo();
						position.date = StringUtil.millToDate(Calendar
								.getInstance().getTimeInMillis());

						boolean ff = false;
						if ((BizApp.getInstance().isWiFiActive() || BizApp
								.getInstance().isNetworkAvailable())
								&& BizApp.getInstance().keeping) {
							if (BizApp.getInstance().getCurrentLocation() == null
									|| BizApp.getInstance().getLat() < 0.0001
									|| BizApp.getInstance().getLon() < 0.0001
									|| System.currentTimeMillis() > (BizApp
											.getInstance().getLocTime() + 70000)) {
								if (!BizApp.getInstance()
										.getmLocationClient().isStarted()) {
									BizApp.getInstance()
											.getmLocationClient().start();
								}
								try {
									sleep(7000);
									int i = 0;
									while (!BizApp.getInstance().isLocation
											&& i < 11) {
										sleep(4000);
										// Log.e("i", "SendReceiver"+i);
										i++;
									}
									if (BizApp.getInstance().isLocation) {
										ff = true;
										BizApp.getInstance().isLocation = false;
									}
									BizApp.getInstance()
											.getmLocationClient().stop();
								} catch (InterruptedException e) {
								}
							} else {
								BizApp.getInstance().getmLocationClient()
										.stop();
							}
						}
						if ((BizApp.getInstance().isWiFiActive() || BizApp
								.getInstance().isNetworkAvailable()) && ff) {
							position.lat = BizApp.getInstance().getLat();
							position.lon = BizApp.getInstance().getLon();
						} else {
							position.lat = 0.0;
							position.lon = 0.0;
						}
						position.address = "";
						position.locationMsg = LocationUtils.getInstance()
								.getLocationMsg();
						position.msgType = 7;
						position.type = 1;
						positions.positions.add(position);
						ShutDownSqlHelper psql = new ShutDownSqlHelper();
						psql.open(BizApp.getInstance().getSqlHelper());
						PositionShutDownInfo pinfo = new PositionShutDownInfo();
						pinfo.setVer(gson.toJson(body));
						pinfo.setPos(gson.toJson(positions));
						pinfo.setType(3);
						psql.addAttribute(pinfo);

					} catch (Exception e) {
//						UserLog.getInstance().writeException(e);
					}
				}
			}.start();
		}catch (Exception e) {
//			UserLog.getInstance().writeException(e);
		}
	}

	private boolean checkSheetTime() {
		try {
			PositionSqlHelper psql = new PositionSqlHelper();
			psql.open(BizApp.getInstance().getSqlHelper());
			PositionAttributeInfo inf = psql.getAttribute();
			if (inf.getDur() == null || inf.getDur() == 0) {
				return false;
			}else{
				int week = 0;
				int hour = 0;
				int min = 0;
				if (inf != null) {
					ContentResolver cv = BizApp.getInstance().getContentResolver();
					String strTimeFormat = android.provider.Settings.System
							.getString(cv,
									android.provider.Settings.System.TIME_12_24);
					Calendar c = Calendar.getInstance();
					week = c.get(Calendar.DAY_OF_WEEK) - 1;
	
					hour = c.get(Calendar.HOUR_OF_DAY);
					min = c.get(Calendar.MINUTE);
	
					// Log.e("time", week + "," + hour + ":" + min);
					String sheet = inf.sheet;
					// Log.e("sheet", sheet);
					String[] sheets = sheet.split(";");
					for (int i = 0; i < sheets.length; i++) {
						String weeks = sheets[i];
						String[] weekc = weeks.split(",");
						if (week == Integer.valueOf(weekc[0])) {
							if (Integer.valueOf(weekc[1]) == 1) {
								if (weekc.length == 2) {
									return true;
								}
								if (weekc.length == 6) {
									// return true;
									if (hour > Integer.valueOf(weekc[2])
											&& (hour < Integer.valueOf(weekc[4]) || hour == Integer
													.valueOf(weekc[4])
													&& min <= Integer
															.valueOf(weekc[5]))) {
										return true;
									}
									if (hour == Integer.valueOf(weekc[2])
											&& min >= Integer.valueOf(weekc[3])
											&& (hour < Integer.valueOf(weekc[4]) || hour == Integer
													.valueOf(weekc[4])
													&& min <= Integer
															.valueOf(weekc[5]))) {
	
										return true;
									}
								}
								if (weekc.length == 10) {
									// return true;
									if (hour > Integer.valueOf(weekc[2])
											&& (hour < Integer.valueOf(weekc[4]) || hour == Integer
													.valueOf(weekc[4])
													&& min <= Integer
															.valueOf(weekc[5]))) {
										return true;
									}
									if (hour == Integer.valueOf(weekc[2])
											&& min >= Integer.valueOf(weekc[3])
											&& (hour < Integer.valueOf(weekc[4]) || hour == Integer
													.valueOf(weekc[4])
													&& min <= Integer
															.valueOf(weekc[5]))) {
										return true;
									}
									if (hour > Integer.valueOf(weekc[6])
											&& (hour < Integer.valueOf(weekc[8]) || hour == Integer
													.valueOf(weekc[8])
													&& min <= Integer
															.valueOf(weekc[9]))) {
										return true;
									}
									if (hour == Integer.valueOf(weekc[6])
											&& min >= Integer.valueOf(weekc[7])
											&& (hour < Integer.valueOf(weekc[8]) || hour == Integer
													.valueOf(weekc[8])
													&& min <= Integer
															.valueOf(weekc[9]))) {
										return true;
									}
								}
							} else {
								return false;
							}
						}
					}
				}
			}
			return false;
		} catch (Exception e) {
//			UserLog.getInstance().writeException(e);
		}
		return false;
	}

}
